<template>
  <div class="container">
    <div class="sec-head">
      <div class="local-name">升级日志</div>
      <div class="delete-btn">
        <el-button
          size="small"
          icon="el-icon-delete"
          class="user-activity-delete"
          @click="deleteSelectedLog"
        >删除所选</el-button>
        <el-button
          size="small"
          icon="el-icon-delete"
          class="user-activity-delete"
          @click="deleteAllLog"
        >清除日志</el-button>
      </div>
    </div>
    <div class="system-log-search-form">
      <search-form
        v-model="searchForm"
        @search="search"
      ></search-form>
    </div>
    <div class="user-activity-log-data-table">
      <data-table
        v-model="sort"
        :tableData="tableData"
        @search="search"
        ref="dataTableComponent"
      ></data-table>
    </div>
    <div class="paging-footer">
      <el-pagination
        background
        @size-change="pageSizeChangeHandler"
        @current-change="currentPageChangeHandler"
        :current-page.sync="currentPage"
        :page-size.sync="pageSize"
        :page-sizes="pageSizes"
        layout="total,sizes, prev, pager, next, jumper"
        :total="totalCount"
        align="right"
      ></el-pagination>
    </div>
    <el-dialog
      title="批量删除"
      :visible.sync="dialogVisible"
      width="600px"
    >
      <div style="padding-bottom:20px">请选择要删除的时间段</div>
      <el-date-picker
        v-model="deleteForm.start"
        type="datetime"
        placeholder="选择删除开始日期时间"
      ></el-date-picker>&nbsp;至
      <el-date-picker
        v-model="deleteForm.end"
        type="datetime"
        placeholder="选择删除结束日期时间"
      ></el-date-picker>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
          type="primary"
          @click="deleteRange"
        >确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import DataTable from './dataTable';
import SearchForm from './searchForm';
import { SortType } from '../../../constants/common';
import { Message, MessageBox } from 'element-ui';
import { validateSearchForm } from './service.js';
import { getUpgradeLogListApi, deleteUpgradeLogRangeApi } from '../../../api/upgradeLog';
import { parseError } from '../../../utils';

export default {
  components: {
    SearchForm,
    DataTable
  },
  data() {
    return {
      upgradeActivityLogIdList: [],
      dialogVisible: false,
      deleteForm: {
        start: new Date(new Date(new Date().toLocaleDateString()).getTime()),
        end: new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000)
      },
      searchForm: {
        btnLoading: false,
        level: '',
        keyword: '',
        start: new Date(new Date(new Date().toLocaleDateString()).getTime()),
        end: new Date(new Date(new Date().toLocaleDateString()).getTime() + 24 * 60 * 60 * 1000),
        method: '',
        url: '',
        requestMessage: '',
        serialNumber: '',
        upgradeStatus: ''
      },
      sort: {
        sortType: SortType.DESC,
        orderBy: 'createdAt'
      },
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      pageSizes: [5, 10, 20, 50, 100],
      totalCount: 0
    };
  },
  created() {
    this.search();
  },
  methods: {
    deleteAllLog() {
      MessageBox.confirm('确认删除全部升级日志吗？', '删除提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          deleteUpgradeLogRangeApi()
            .then(res => Message.success(`成功删除${res.count}条升级日志`))
            .catch(error => Message.error(parseError(error)))
            .finally(() => this.search());
        })
        .catch(() => {});
    },
    deleteSelectedLog() {
      this.upgradeActivityLogIdList = this.$refs.dataTableComponent.upgradeActivityLogIdList;
      if (this.upgradeActivityLogIdList.length == 0) return Message.warning('请选择要删除的升级日志内容');
      MessageBox.confirm(`确认删除${this.upgradeActivityLogIdList.length}条升级日志吗？`, '删除提示', {
        type: 'warning',
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(() => {
          deleteUpgradeLogRangeApi(this.upgradeActivityLogIdList)
            .then(res => Message.success(`成功删除${res.count}条升级日志`))
            .catch(error => Message.error(parseError(error)))
            .finally(() => this.search());
        })
        .catch(() => {});
    },
    search() {
      this.searchForm.btnLoading = true;
      getUpgradeLogListApi(
        this.currentPage - 1,
        this.pageSize,
        this.sort.sortType,
        this.sort.orderBy,
        this.searchForm.start,
        this.searchForm.end,
        this.searchForm.level,
        this.searchForm.serialNumber,
        this.searchForm.keyword,
        this.searchForm.method,
        this.searchForm.url,
        this.searchForm.requestMessage,
        this.searchForm.upgradeStatus
      )
        // .then(res => {
        //   this.totalCount = res.total_count;
        //   this.tableData = res.data;
        // })
        .then(({ total_count, data }) => {
          this.totalCount = total_count;
          this.tableData = data.map(upgradeActiveLog => {
            return {
              id: upgradeActiveLog.id,
              level: upgradeActiveLog.level,
              ip: upgradeActiveLog.ip,
              url: upgradeActiveLog.method + ' ' + upgradeActiveLog.url,
              serialNumber: upgradeActiveLog.serial_number,
              requestMessage: upgradeActiveLog.request_message,
              responseCode: upgradeActiveLog.response_code,
              deviceVersion: upgradeActiveLog.device_version,
              upgradeStatus: upgradeActiveLog.upgrade_status,
              responseMessage: upgradeActiveLog.response_message,
              interval: upgradeActiveLog.interval,
              createdAt: upgradeActiveLog.created_at
            };
          });
        })
        .catch(error => Message.error(parseError(error)))
        .finally(() => (this.searchForm.btnLoading = false));
    },
    showDelete() {
      this.dialogVisible = true;
    },
    pageSizeChangeHandler() {
      this.currentPage = 1;
      this.search();
    },
    currentPageChangeHandler() {
      this.search();
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  .sec-head {
    display: flex;
    justify-content: space-between;
    .local-name {
      padding-top: 10px;
      padding-left: 10px;
      margin-bottom: 10px;
      // padding: 10px 0 10px 10px;
      font-size: 24px;
      font-weight: 800;
    }
    .delete-btn {
      margin-top: 10px;
      margin-right: 10px;
      .user-activity-delete {
        color: #fff;
        background-color: #f24d1f;
      }
    }
  }
  .user-activity-log-data-table {
    background-color: #fff;
    padding: 10px;
    margin: 0 10px;
  }

  .local-name {
    font-size: 24px;
    font-weight: 800;
  }
  .paging-footer {
    padding: 10px 10px;
    background-color: #fff;
    margin: 0 10px;
  }
  .system-log-search-form {
    background: #fff;
    margin: 0 10px;
    // margin-bottom: 10px;
    // padding: 15px 15px 0 15px;
  }
}
</style>
